/*
 * @Description: 赋权审核列表
 * @Author: Rfan
 * @Date: 2022-03-29 13:57:08
 * @LastEditTime: 2023-02-07 17:35:04
 */

import { FC, useEffect, useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import dayjs from 'dayjs';
import { fetchRightApplyByFormNo } from '@/api/workFlow/apply';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useRightApproveContext } from '../../contexts/RightApproveContext';
import ApproveDialog from '../dialogs/ApproveDialog';
import { EnumApproveDialogTypes, EnumApproveNavTypes } from '../../dictionaries';
import styles from '../../styles/list.module.scss';

const cx = classNames.bind(styles);

const { Column } = Table;

const ApproveList: FC = () => {
  const formatMessage = useFormatMessage();
  const { approveList, getApproveList, selectItems, approveNav, getApproveCompleteList } =
    useRightApproveContext();
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogData, setDialogData] = useState({});
  const [datas, setDatas] = useState({});
  const [listQuery, setListQuery] = useState<any>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });

  useEffect(() => {
    const assignee = JSON.parse(localStorage.getItem('userInfo')).id;
    console.log('assignee', assignee);

    if (assignee) {
      setListQuery((state: any) => {
        return {
          ...state,
          param: {
            ...listQuery.param,
            assignee,
            assigneeType: 1,
            modelType: 'QUAN_XIAN_FLOW'
          }
        };
      });
    }
  }, [approveNav]);

  useEffect(() => {
    if (listQuery?.param?.assignee) {
      console.log('wiuwiw');

      setLoading(true);
      const method =
        approveNav === EnumApproveNavTypes.Undo
          ? getApproveList(listQuery)
          : getApproveCompleteList(listQuery);
      method
        .then((res: any) => {
          console.log('back', res);
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description: 打开通知弹窗方法
   */
  const showApproveDialogFunc = (record: any, type: EnumApproveDialogTypes) => {
    setDatas({ ...record, type });
    const apply = approveNav === EnumApproveNavTypes.Undo ? record.applyFormNo : record.businessKey;
    fetchRightApplyByFormNo(apply)
      .then((res) => {
        const { data } = res;
        setDialogData(data);
      })
      .then(() => setDialogVisible(true));
  };

  // 表格选项相关设置
  const onSelectChange = (selectedRowKeys: number[]): void => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
  };

  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  // 切换页码触发
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state: any) => {
      return {
        ...state,
        pageNo: page,
        pageSize
      };
    });
  };

  return (
    <div className={cx('approve-list')}>
      <Table
        dataSource={approveList}
        loading={loading}
        rowKey="processInstanceId"
        bordered
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex={['applyForm', 'id']} key="id" align="center" />
        <Column
          title="申请标题"
          key="title"
          align="center"
          render={(record) => (
            <span>
              {record.startUserName}的{record.processName}
            </span>
          )}
        />
        {/* <Column title="提供单位" align="center" /> */}
        <Column title="申请人" dataIndex={'startUserName'} key="proposer" align="center" />
        {/* <Column
          title="利用方式"
          dataIndex={['applyForm', 'useTypeEntity']}
          key="useTypeEntity"
          align="center"
        /> */}
        <Column
          title="状态"
          dataIndex={approveNav === EnumApproveNavTypes.Undo ? 'status' : 'state'}
          key="status"
          align="center"
        />
        {/* <Column title="通知状态" align="center" /> */}
        <Column
          title="申请时间"
          dataIndex={'startTime'}
          key="applyTime"
          align="center"
          render={(text) => text && dayjs(text).format('YYYY-MM-DD HH:mm:ss')}
        />
        {approveNav === EnumApproveNavTypes.Undo ? (
          ''
        ) : (
          <Column
            title="审批时间"
            dataIndex="endTime"
            key="endTime"
            align="center"
            render={(text) => text && dayjs(text).format('YYYY-MM-DD HH:mm:ss')}
          />
        )}
        <Column
          title="剩余利用天数"
          dataIndex={['applyForm', 'useDay']}
          key="useDay"
          align="center"
        />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          align="center"
          render={(_text, record: any) => (
            <Space>
              {approveNav === EnumApproveNavTypes.Undo ? (
                <Button
                  type="link"
                  onClick={() => {
                    showApproveDialogFunc(record, EnumApproveDialogTypes.Approve);
                  }}
                >
                  查看申请
                </Button>
              ) : (
                <Button
                  type="link"
                  onClick={() => {
                    showApproveDialogFunc(record, EnumApproveDialogTypes.View);
                  }}
                >
                  查看详情
                </Button>
              )}
            </Space>
          )}
        />
      </Table>
      {useMemo(
        () =>
          JSON.stringify(dialogData) !== '{}' && (
            <ApproveDialog
              visible={dialogVisible}
              data={dialogData}
              datas={datas}
              onClose={() => {
                setDialogVisible(false);
              }}
            />
          ),
        [dialogVisible, dialogData]
      )}
    </div>
  );
};

export default ApproveList;
